<?php

namespace App\Http\Controllers\Foundation;


use App\Events\Event;
use App\Events\StudentEvent;
use App\Model\Business\Appointment;
use App\Model\Business\ClasseStuden;
use App\Model\Business\Demoment;
use App\Model\Business\ScheduleStuden;
use App\Model\System\NoticeConfig;
use App\Model\System\SystemConfig;
use Illuminate\Http\Request;
use App\Model\System\User;
use Laravel\Lumen\Routing\Controller as BaseController;


use App\Model\Foundation\Student;
use App\Http\Controllers\MessagePacket;
use Mockery\CountValidator\Exception;


class StudentController extends BaseController
{
    use MessagePacket;


    function  __construct(){}


    /**
     * 获取单一用户的信息
     * @param $id
     * @return packetMessage
     */
    function getStudent($id)
    {
        $id = intval($id);
        $student = Student::find($id);
        $account = User::where('userid',$student->userid)->pluck('account')->first();
        $student->account = $account;
        if(empty($student)){
            return $this->fail($student, '数据不存在');
        }
        return $this->success($student);
    }


    /**
     * 批量查询学生列表
     * @param Request $request
     * @return packetMessage
     */
    function getStudents(Request $request)
    {
        $name = '';
        if($request->has('name')) $name= $request->get('name');
        $student = Student::where('name', 'like', "%$name%");
        if($request->has('mobile')){
            $student->orwhere('mobile', 'like', "%{$request->get('mobile')}%");
        }
        if($request->has('ClassInNo')){
            $student->orwhere('ClassInNo', 'like', "%".$request->get('ClassInNo')."%");
        }
        # 需要／不需要 分页
        if($request->has('page')) {
            $limit = 30;
            if ($request->has('perPage')) {
                $limit = $request->get('perPage');
            }
            $students = $student->paginate($limit)->toArray();
            $data['list'] = $students['data'];
            unset($students['data']);
            $data['pager'] = $students;
        }else{
            $data = $student->get();
        }
        #
        if(empty($data)){
            return $this->fail($data, '数据不存在');
        }
        return $this->success($data);
    }


    /**
     * 添加一个学员
     * @param Request $request
     * @return packetMessage
     */
    function  addStudent(Request $request)
    {
        try{
            $fields = $request->all();
            # 排重
            $student = Student::where('ClassInNo', $fields['ClassInNo'])->first();
            if($student){
                return $this->fail(false,'学生ClassIn 账号已经存在.');
            }
            # 学生表电话号排重
            $student = Student::where('mobile', $fields['mobile'])->first();
            if($student){
                return $this->fail(false,'手机号已存在');
            }
            
            # 创建
            $student = new Student($fields);


            #抛出用户
            $password = '';
            if($request->has('password')) $password = $request->get('password');
            $this->dispatchEvent($student, Event::CREATE, $password);

            # 关联用户表
            $user = User::where('number',$fields['mobile'])->first();
            if(empty($user)) {
                $obj = new User();
                $obj->userid = User::generateID();
                $obj->type = User::STUDENT;
                $obj->email = $fields['email'];
                $obj->number = $fields['mobile'];
                $obj->islock = User::UNLOCK;
                $password = '123456';
                $config = SystemConfig::find(1);
                if($config){
                    $password = $config->defaultpassword;
                }
                $obj->setSecurityCode($password);
                $obj->updateCreator();
                $student->userid = $obj->userid;
                $obj->save();

            }
            else {
                $student->userid = $user->userid;
            }
            $student->save();

            #新建提醒  默认开启微信及邮件通知，课前60分钟提醒，每天12点提醒。
            $obj = new NoticeConfig([
                        'utype'=>2,
                        'uid'=>$student->studentuid,
                        'ntype'=>1,
                        'byemail'=>1,
                        'bywechat'=>1,
                        'ahead'=>60,
                        'perday'=>12]);
            $obj->save();
            $obj2 = new NoticeConfig(['utype'=>2, 'uid'=>$student->studentuid, 'ntype'=>2]);
            $obj2->save();
            return $this->success($student);
        }catch (\Exception $e) {
            $student->delete();
            return $this->fail(false, '保存失败: ' . $e->getMessage());
        }
    }


    /**
     * 更新某个学员的信息
     * @param Request $request
     * @return packetMessage
     */
    function  updateStudent(Request $request, $id)
    {
        try{
            $uid = 0;
            if(empty($id)){
                $uid = $request->studentuid;
            }else{
                $uid = $id;
            }
            $student = Student::find($uid);
            if(User::updateMobile($request, $student) === false){
                return $this->fail(false,'手机号已经存在，不能更改.');
            }
            # 抛出事件
            $this->dispatchEvent($student, Event::UPDATE);

            $student->update($request->all());
            return $this->success($student);
        }catch (\Exception $e){
            return $this->fail(false,'修改失败:'.$e->getMessage());
        }
    }


    /**
     * 删除某个学员
     * @param $id
     * @return packetMessage
     */
    function  deleteStudent($id)
    {
        try{
            $student = Student::find($id);
	        $demo = Demoment::where('studentuid', $id)->first();
            if($demo){
                return $this->fail(false, '请先清除学生的试听课约课信息');
            }
            $appoint = Appointment::where('studentuid', $id)->first();
            if($appoint){
                return $this->fail(false, '请先清除学生的正式课约课信息');
            }
            $classe = ClasseStuden::where('studentuid', $id)->first();
            if($classe){
                return $this->fail(false, '请先清除学生的班级信息');
            }

            # 清除学生表
            Student::destroy($id);
            return $this->success(true);
        }catch (\Exception $e){
            return $this->fail(false, '删除失败:'.$e->getMessage());
        }
    }


    /**
     * 抛出事件
     * @param Student $student
     * @param $action
     * @return mixed
     * @throws \Exception
     */
    protected function dispatchEvent(Student $student, $action, $password=null)
    {
        try{
            $event = new StudentEvent($student, $action, $password);
            event($event);
        }catch (\Exception $e){
            throw $e;
            return $e->getMessage();
        }
    }

    /**
     * 关联用户id
     * @param Request $request
     * @param $id：userid
     * @return array
     */
    function associate(Request $request, $id)
    {
        if(!$request->has('userid')){
            return $this->fail(false, '参数不全');
        }
        $obj = Student::find($id);
        $obj->userid = $request->userid;
        if($obj->save()){
            return $this->success(true);
        }
        return $this->fail(false, '关联失败');
    }

    /**
     * 根据userid获取学生信息
     * @param $id：userid
     * @return array
     */
    function getStudentByUserid($id)
    {
        $userid = intval($id);
        $student = Student::where('userid',$userid)->first();
        if(empty($student)){
            return $this->fail($student, '数据不存在');
        }
        return $this->success($student);
    }
}
